const app = getApp();
import Api from '@/services/api.js'
export default {
  data() {
    return {
      list: [], // 部门列表
      activeDep: {}, // 当前选中的部门对象
    }
  },
  computed: {
    privacyData() {
      return this.$store.state.privacyData;
    },
    companyInfo() {
      return this.$store.state.companyInfo;
    },
    // 老板主看的部门
    bossDepartments() {
      /**
       * 因为人力部门和管理部门是固定在第一第二条
       * 所以 如果是HR角色不显示人力部门
       */
      const startIdx = this.isHR ? 1 : 0;
      return this.list.slice(startIdx, 2)
    },
    hrDepartments() {
      return this.list.slice(2, this.list.length)
    },
    // 是否是HR
    isHR() {
      return this.privacyData.roles.includes('hr')
    }
  },
  onLoad() {
  },
  onShow() {
    this.getDepartmentsByEnterpriseId();
  },
  methods: {
    // 根据企业id获取部门信息
    async getDepartmentsByEnterpriseId(arg = {}) {
      this.list = await this.$Serv.getEnterpriseDepartments(arg)
    },
    handleAdd() {
      // 新增时重置当前选中的部门数据 避免重复
      this.activeDep = {};
      this.$refs.inputModal.toggleModal(true)
    },
    // 列表点击事件
    handleItem(e) {
      const { item, type = '' } = e.currentTarget.dataset;
      let url = '/enterpriseMgmt/positionMgmt/index';
      uni.navigateTo({ 
        url: url + `?department=${JSON.stringify(item)}`,
        events: {
          // 更新数据的回调
          refresh: (e) => {
            this.getDepartmentsByEnterpriseId(e);
          }
        }
       })
    },
    // 编辑事件
    handleEdit(e) {
      const { item } = e.currentTarget.dataset;
      this.activeDep = item;
      this.$refs.inputModal.toggleModal(true)
    },
    // 新增部门事件
    async onConfirm(inputValue) {
      const { id } = this.activeDep;
      let url = Api.addDepartmentByEnterpriseId;
      let data = {
        enterpriseId: this.companyInfo.enterpriseId,
        departmentTitle: inputValue
      }
      // 如果有id 表示编辑
      if (id) {
        url = Api.updateEnterpriseDepartment;
        data.departmentId = id;
        delete data.enterpriseId;
      }
      const { code } = await this.$request({ url, method: 'POST', data })
      if (code === 200) {
        uni.showToast({ title: '操作成功', icon: 'none' });
        this.$refs.inputModal.toggleModal(false);
        this.getDepartmentsByEnterpriseId();
      }
    },
  }
}